package com.example.mqttdemo;

import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.handler.annotation.Header;

@Configuration
public class SpringConfig {

    @Bean
    public MqttConnectOptions getMqttConnectOptions(){
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setUserName("emqx_u");
        //配置broker挂掉之后存储在broker内的消息是否清楚
        mqttConnectOptions.setCleanSession(false);
        mqttConnectOptions.setPassword("emqx_p".toCharArray());
        //tcp/ip 传输底层实现
        mqttConnectOptions.setServerURIs(new String[]{"tcp://140.143.183.52:1883"});
        //存活时间
        mqttConnectOptions.setKeepAliveInterval(30);
        // 设置超时时间 单位为秒
        mqttConnectOptions.setConnectionTimeout(15);
        //最大消息数量
        mqttConnectOptions.setMaxInflight(100000);
        // 此处初始化设置对应的遗言消息设置last will
//        MqttRule mqttRule = mqttRuleRepo.findByAction(MqttMessageAction.LAST_WILL);
//        MqttMessageDTO mqttMessageDTO = new MqttMessageDTO();
//        MqttMessageDTO.Payload payload = mqttMessageDTO.getPayload();
//        DeviceModel deviceModel = new DeviceModel();
//        deviceModel.setDeviceId(VemUtils.getServiceId());
//        payload.setProductId(productId);
//        payload.setAction(MqttMessageAction.LAST_WILL);
//        payload.setModel(mqttRule.getModel());
//        payload.setData((JSONObject) JSONObject.toJSON(deviceModel));
//        mqttConnectOptions.setWill(mqttRule.getTopic(), JSONObject.toJSONString(mqttMessageDTO).getBytes(), mqttRule.getQos(), false);
        return mqttConnectOptions;
    }


    /*****
     * 创建MqttPahoClientFactory，设置MQTT Broker连接属性，如果使用SSL验证，也在这里设置。
     * @return
     */
    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(getMqttConnectOptions());
        return factory;
    }

    @Bean
    public MessageChannel mqttInputChannel() {
        return new DirectChannel();
    }

    @Bean
    public MessageProducer inbound() {
        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("consumerClient",
                mqttClientFactory(), "topic1", "topic2");
        adapter.setCompletionTimeout(5000);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(1);
        adapter.setOutputChannel(mqttInputChannel());
        return adapter;
    }

    @Bean
    //ServiceActivator注解表明当前方法用于处理MQTT消息，inputChannel参数指定了用于消费消息的channel。
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public MessageHandler handler() {
        return message -> {
            String payload = message.getPayload().toString();
            String topic = message.getHeaders().get("mqtt_receivedTopic").toString();
            // 根据topic分别进行消息处理。
            if (topic.equals("topic1")) {
                System.out.println("topic1: 处理消息 " + payload);
            } else if (topic.equals("topic2")) {
                System.out.println("topic2: 处理消息 " + payload);
            } else {
                System.out.println(topic + ": 丢弃消息 " + payload);
            }
        };
    }


    // 发送消息

    @Bean
    public MessageChannel mqttOutboundChannel() {
        return new DirectChannel();
    }

    /*****
     * 发送消息和消费消息Channel可以使用相同MqttPahoClientFactory
     * @return
     */
    @Bean
    @ServiceActivator(inputChannel = "mqttOutboundChannel")
    public MessageHandler outbound() {
        // 在这里进行mqttOutboundChannel的相关设置
        MqttPahoMessageHandler messageHandler =
                new MqttPahoMessageHandler("publishClient", mqttClientFactory());
        messageHandler.setAsync(true); //如果设置成true，发送消息时将不会阻塞。
        messageHandler.setDefaultTopic("testTopic");
        return messageHandler;
    }

}
